﻿using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Core.SqlBuilder;
using Kingdee.BOS.Core.Metadata;
using System;
using System.Collections.Generic;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.List.PlugIn.Args;
using Kingdee.BOS.Core.Permission.Args;
using Kingdee.BOS.Core.List.PlugIn;
using System.ComponentModel;
using Kingdee.BOS.Core.Bill;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.List;
using Kingdee.BOS.Core.Metadata.Util;
using SPCom.Junit.BusinessPlugIn.SaleOrderAdjust.BillListPlugIn.Service.VO;

namespace SPCom.Junit.BusinessPlugIn.SaleOrderAdjust.BillListPlugIn
{

    /// <summary>
    ///  销售订单--表单插件
    /// </summary>
    [Kingdee.BOS.Util.HotUpdate]
    [Description("SaleOrderAdjustList")]
    public class SalrOrderBillList : AbstractListPlugIn
    {
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="e"></param>
        public override void ListInitialize(ListInitializeEventArgs e)
        {
            PrintEventInfo("ListInitialize", e);
            base.ListInitialize(e);
        }
        /// <summary>
        /// 菜单点击事件，表单插件同样适用
        /// </summary>
        /// <param name="e"></param>
        public override void BarItemClick(BarItemClickEventArgs e)
        {
            PrintEventInfo("BarItemClick", e);
            base.BarItemClick(e);
            switch (e.BarItemKey.ToUpperInvariant())
            {
                //case "TBDELETE": 列表工具栏按钮事件，通过按钮Key[大写]来区分那个按钮事件
                //break;
                case "":
                    break;
                default:
                    break;
            }
        }


        /// <summary>
        /// 菜单点击后处理事件，表单插件同样适用 NBDO_tbBtn_SaleOrderList_Adjust
        /// </summary>
        /// <param name="e"></param>
        public override void AfterBarItemClick(AfterBarItemClickEventArgs e)
        {
            PrintEventInfo("AfterBarItemClick", e);
            if (e.BarItemKey.Equals("NBDO_SaleOrderList_Adjust"))
            {
                // 1.获取选择的行数据
                ListSelectedRowCollection selectedRows = this.ListView.SelectedRowsInfo;

                // 2.检查是否选中
                string[] listKey = selectedRows.GetPrimaryKeyValues();
                if (listKey.Length == 0)
                {
                    this.View.ShowMessage("请选择销售订单信息!", MessageBoxType.Notice);
                    return;
                }
                else
                {
                    // 3.打开添加单据页面
                    BillShowParameter billShowParameter = new BillShowParameter();
                    billShowParameter.PKey = "100012";
                    billShowParameter.FormId = "NBDO_SP_SaleOrder_Edit";
                    billShowParameter.Status = OperationStatus.EDIT;
                    billShowParameter.PageId = Guid.NewGuid().ToString();
                    billShowParameter.OpenStyle.ShowType = ShowType.MainNewTabPage;

                    // 4.获取数据包，转换成行
                    DynamicObjectCollection dataCollection = this.ListModel.GetData(selectedRows);
                    List<AdjustSaleOrderVo> saleBillAdjustList = new List<AdjustSaleOrderVo>();   
                    for (int i = 0; i < dataCollection.Count; i++)
                    {
                        AdjustSaleOrderVo vo = new AdjustSaleOrderVo();
                        // 物料信息
                        DynamicObject materialInfo = dataCollection[i]["FMaterialId_Ref"] as DynamicObject; 
                        vo.MaterialCode = dataCollection[i]["FMaterialId_Id"].ToString();
                        vo.MaterialName = materialInfo["Name"].ToString(); 
                        vo.MaterialId = materialInfo["Id"].ToString();
                        vo.MaterialCode = materialInfo["Number"].ToString();
                        // 获取客户
                        DynamicObject customerInfo = dataCollection[i]["FCustId_Ref"] as DynamicObject;
                        vo.CustomerName = customerInfo["Name"].ToString();
                        // 计量单位
                        DynamicObject unitInfo = dataCollection[i]["FPriceUnitId_Ref"] as DynamicObject;
                        vo.UnitName = unitInfo["Name"]?.ToString();
                        // TM
                        vo.FEntryId = dataCollection[i]["FID"].ToString();
                        vo.SaleOrderNo = dataCollection[i]["FBILLNO"].ToString();
                        vo.Price = 0;
                        vo.AdjustPrice = 0;

                        saleBillAdjustList.Add(vo);
                    }
                    // 5.绑定参数
                    billShowParameter.CustomComplexParams["SaleBillAdjustData"] = saleBillAdjustList;
                    this.View.ShowForm(billShowParameter);
                }
            }
        }


        /// <summary>
        /// 对列表数据追加过滤或是排序，推荐通过过滤方案进行处理，如果是特殊的强制过滤，可以在这个位置进行处理
        /// </summary>
        /// <param name="e"></param>
        public override void PrepareFilterParameter(FilterArgs e)
        {
            base.PrepareFilterParameter(e);
            e.AppendQueryFilter("");
            e.AppendQueryOrderby("");
        }


        /// <summary>
        /// 单元格格式化事件
        /// </summary>
        /// <param name="Args"></param>
        public override void CellFormat(CellEventArgs e)
        {
            base.CellFormat(e);
        }
        /// <summary>
        /// 单元格的双击事件
        /// </summary>
        /// <param name="Args"></param>
        public override void CellDbClick(CellEventArgs e)
        {
            base.CellDbClick(e);
        }
        /// <summary>
        /// 按钮点击前
        /// </summary>
        /// <param name="e"></param>
        public override void BeforeButtonClick(MenuArgs e)
        {
            base.BeforeButtonClick(e);
        }
        /// <summary>
        /// 按钮点击后
        /// </summary>
        /// <param name="e"></param>
        public override void AfterButtonClick(MenuArgs e)
        {
            base.AfterButtonClick(e);
        }
        /// <summary>
        /// 菜单点击前
        /// </summary>
        /// <param name="e"></param>
        public override void BeforeMenuClick(MenuArgs e)
        {
            base.BeforeMenuClick(e);
        }
        /// <summary>
        /// 菜单点击后
        /// </summary>
        /// <param name="e"></param>
        public override void AfterMenuClick(MenuArgs e)
        {
            base.AfterMenuClick(e);
        }
        /// <summary>
        /// 列表创建列事件
        /// </summary>
        /// <param name="e"></param>
        public override void ListCreateColumns(ListCreateColumnsEventArgs e)
        {
            base.ListCreateColumns(e);
        }
        /// <summary>
        /// 列表行双击事件
        /// </summary>
        /// <param name="e">事件参数包</param>
        public override void ListRowDoubleClick(ListRowDoubleClickArgs e)
        {
            base.ListRowDoubleClick(e);
        }
        /// <summary>
        /// 下推过程，展示可选目标单据；捕获此事件，调整可选的单据类型
        /// </summary>
        /// <param name="e"></param>
        public override void OnShowConvertOpForm(ShowConvertOpFormEventArgs e)
        {
            base.OnShowConvertOpForm(e);
        }
        /// <summary>
        /// 选单/下推过程, 确定单据转换规则
        /// </summary>
        /// <param name="e"></param>
        public override void OnGetConvertRule(GetConvertRuleEventArgs e)
        {
            base.OnGetConvertRule(e);
        }
        /// <summary>
        /// 上/下查过程，获得上/下查结果；捕获此事件，调整上/下查结果
        /// </summary>
        /// <param name="e"></param>
        public override void OnShowTrackResult(ShowTrackResultEventArgs e)
        {
            base.OnShowTrackResult(e);
        }
        /// <summary>
        /// 列表行数据格式化
        /// </summary>
        /// <param name="args"></param>
        public override void OnFormatRowConditions(ListFormatConditionArgs args)
        {
            base.OnFormatRowConditions(args);
        }
        /// <summary>
        /// 触发取数前事件,本方法用于采用临时表做分页查询的列表
        /// </summary>
        /// <param name="e"></param>
        public override void BeforeGetDataForTempTableAccess(BeforeGetDataForTempTableAccessArgs e)
        {
            base.BeforeGetDataForTempTableAccess(e);
        }
        /// <summary>
        /// 在构建完sql取数参数之后
        /// </summary>
        /// <param name="e"></param>
        public override void AfterCreateSqlBuilderParameter(SqlBuilderParameterArgs e)
        {
            base.AfterCreateSqlBuilderParameter(e);
        }
        /// <summary>
        /// 触发组装数据规则
        /// </summary>
        /// <param name="e"></param>
        public override void PrepareFuncPermissionDataRule(DataRuleArgs e)
        {
            base.PrepareFuncPermissionDataRule(e);
        }
        /// <summary>
        ///  触发建立过滤控件事件
        /// </summary>
        /// <param name="e"></param>
        public override void CreateFilterEditorControl(CreateControlEventArgs e)
        {
            base.CreateFilterEditorControl(e);
        }
        /// <summary>
        /// 完成取数后事件接口
        /// </summary>
        public override void AfterGetData()
        {
            base.AfterGetData();
        }
        /// <summary>
        /// 列表格式化接口
        /// </summary>
        /// <param name="args"></param>
        public override void FormatCellValue(FormatCellValueArgs args)
        {
            base.FormatCellValue(args);
        }
        /// <summary>
        /// 复制单据事件
        /// </summary>
        /// <param name="e"></param>
        public override void BatchCopyData(BatchCopyDataEventArgs e)
        {
            base.BatchCopyData(e);
        }
        /// <summary>
        /// 单据复制完毕事件
        /// </summary>
        /// <param name="e"></param>
        public override void AfterBatchCopyData(BatchCopyDataEventArgs e)
        {
            base.AfterBatchCopyData(e);
        }
        /// <summary>
        /// 超链接点击事件
        /// </summary>
        /// <param name="entryKey"></param>
        /// <param name="row"></param>
        /// <param name="fieldKey"></param>
        public override void EntryHyperlinkButtonClick(HyperlinkButtonClickArgs e)
        {
            base.EntryHyperlinkButtonClick(e);
        }
        /// <summary>
        /// 构建完过滤字段之后
        /// </summary>
        /// <param name="e"></param>
        public override void AfterCreateFilterField(Kingdee.BOS.Core.List.PlugIn.Args.AfterCreateFilterFieldEventArgs e)
        {
            base.AfterCreateFilterField(e);
        }
        /// <summary>
        ///  下推过程中，目标单改变事件
        /// </summary>
        /// <param name="e"></param>
        public override void OnTargetBillChanged(TargetBillChangedEventArgs e)
        {
            base.OnTargetBillChanged(e);
        }
        /// <summary>
        /// 创建自定义列表头事件
        /// </summary>
        /// <param name="e"></param>
        public override void CreateListHeader(CreateListHeaderEventArgs e)
        {
            base.CreateListHeader(e);
        }
        /// <summary>
        /// 替换构造列表查询的from语句
        /// </summary>
        /// <param name="e"></param>
        public override void ReplaceEntityTable(ReplaceEntityTableArgs e)
        {
            base.ReplaceEntityTable(e);
        }
        #region private method
        /// <summary>
        /// 事件执行次数计数器
        /// </summary>
        private int counter;
        /// <summary>
        /// 事件执行次数计数器
        /// </summary>
        private int Counter
        {
            get { return ++counter; }
        }
        /// <summary>
        /// 输出事件执行日志
        /// </summary>
        /// <param name="eventName">事件名称</param>
        /// <param name="args">事件参数</param>
        private void PrintEventInfo(string eventName, params object[] args)
        {
            var formId = GetFormId();
            var parameters = string.Empty;
            try
            {
                //parameters = Newtonsoft.Json.JsonConvert.SerializeObject(args);// 性能较差，可能会导致页面假死
            }
            catch
            {
            }
            var log = string.Format("序号:{0},执行时间:{1},表单Id:{2},事件名称:{3},事件参数:{4}", Counter, DateTime.Now.ToString("yyyy -MM-dd HH:mm:ss.fff"), formId, eventName, parameters);
            System.Diagnostics.Debug.Print(log);
            Kingdee.BOS.Log.Logger.Error("EVENT", log, null);
        }
        /// <summary>
        /// 获取业务对象标识
        /// </summary>
        /// <returns></returns>
        private string GetFormId()
        {
            var formId = string.Empty;
            if (this.View != null && this.View.BillBusinessInfo != null)
            {
                formId = this.View.BillBusinessInfo.GetForm().Id;
            }
            return formId;
        }

        /// <summary>
        /// queryservice取数方案，通过业务对象来获取数据，推荐使用
        /// </summary>
        /// <returns></returns>
        private DynamicObjectCollection GetQueryDatas()
        {
            QueryBuilderParemeter paramCatalog = new QueryBuilderParemeter()
            {
                FormId = "",//取数的业务对象
                FilterClauseWihtKey = "",//过滤条件，通过业务对象的字段Key拼装过滤条件
                SelectItems = SelectorItemInfo.CreateItems("", "", ""),//要筛选的字段【业务对象的字段Key】，可以多个，如果要取主键，使用主键名
            };

            DynamicObjectCollection dyDatas = Kingdee.BOS.ServiceHelper.QueryServiceHelper.GetDynamicObjectCollection(this.Context, paramCatalog);
            return dyDatas;
        }
        #endregion
    }
}